<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="70px">
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input v-model="queryParams.noticeTitle" placeholder="请输入公告标题" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="公告类型" prop="noticeType">
        <el-select v-model="queryParams.noticeType" placeholder="请选择公告类型" clearable style="width: 200px">
          <el-option 
            v-for="type in noticeTypeOptions" 
            :key="type.value" 
            :label="type.label" 
            :value="type.value" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发起方" prop="initiator">
        <el-input v-model="queryParams.initiator" placeholder="请输入发起方" clearable style="width: 200px" />
      </el-form-item>
      <!-- <el-form-item label="开始日期" prop="startDate">
        <el-date-picker 
          v-model="queryParams.startDate" 
          type="date" 
          placeholder="选择开始日期" 
          style="width: 200px" 
        />
      </el-form-item> -->
      <el-form-item label="创建时间" prop="createDate">
        <el-date-picker 
          v-model="queryParams.createDate" 
          type="datetimerange" 
          range-separator="-" 
          start-placeholder="开始日期时间" 
          end-placeholder="结束日期时间" 
          style="width: 360px" 
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleEdit()"
         
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        
        >删除</el-button>
      </el-col>
      
    </el-row>

    <!-- 表格 -->
    <el-table 
      border 
      v-loading="loading" 
      :data="noticeList" 
      @selection-change="handleSelectionChange" 
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="公告标题" prop="noticeTitle" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ scope.row.noticeTitle }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公告类型" prop="noticeType" min-width="120">
        <template #default="scope">
          <el-tag :type="getNoticeTypeTagType(scope.row.noticeType)">
            {{ scope.row.noticeType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="公告编号" prop="noticeNo" min-width="120">
        <template #default="scope">
          <span>{{ scope.row.noticeNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发起方" prop="initiator" min-width="120">
        <template #default="scope">
          <span>{{ scope.row.initiator }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公告内容" prop="content" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ scope.row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件" prop="fileUrl" min-width="150">
        <template #default="scope">
          <el-popover
            placement="top-start"
            :width="300"
            trigger="hover"
            v-if="scope.row.fileUrl && scope.row.fileUrl.split(',').length > 1"
          >
            <template #default>
              <div v-for="(fileUrl, idx) in scope.row.fileUrl.split(',').slice(1)" :key="idx" style="margin-bottom: 8px;">
                <el-link 
                  type="primary" 
                  :href="fileUrl.trim()" 
                  target="_blank"
                >
                  {{ getFileName(fileUrl.trim()) }}
                </el-link>
              </div>
            </template>
            <template #reference>
              <span style="cursor: pointer; color: #409eff; display: flex; align-items: center;">
                <el-link 
                  type="primary" 
                  :href="scope.row.fileUrl.split(',')[0].trim()" 
                  target="_blank"
                >
                  {{ getFileName(scope.row.fileUrl.split(',')[0].trim()) }}
                </el-link>
                <el-icon style="margin-left: 4px; font-size: 12px;"><ArrowDown /></el-icon>
              </span>
            </template>
          </el-popover>
          <el-link 
            v-else-if="scope.row.fileUrl"
            type="primary" 
            :href="scope.row.fileUrl.trim()" 
            target="_blank"
          >
            {{ getFileName(scope.row.fileUrl.trim()) }}
          </el-link>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="抄送方" prop="sender" min-width="120">
        <template #default="scope">
          <span>{{ scope.row.sender || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公告时间" prop="noticeDate" min-width="180">
        <template #default="scope">
          <span>{{ scope.row.noticeDate }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="模版名称" prop="templateName" min-width="120">
        <template #default="scope">
          <span>{{ scope.row.templateName || '-' }}</span>
        </template>
      </el-table-column> -->
       <el-table-column label="创建时间" prop="createDate" min-width="180">
        <template #default="scope">
          <span>{{ scope.row.createDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑公告' : '新增公告'" 
      width="800px" 
      @close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公告标题" prop="noticeTitle" required>
              <el-input v-model="dialogForm.noticeTitle" placeholder="请输入公告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告类型" prop="noticeType" required>
              <el-select v-model="dialogForm.noticeType" placeholder="请选择公告类型" style="width: 100%">
                <el-option 
                  v-for="type in noticeTypeOptions" 
                  :key="type.value" 
                  :label="type.label" 
                  :value="type.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告编号" prop="noticeNo" required>
              <el-input v-model="dialogForm.noticeNo" placeholder="请输入公告编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发起方" prop="initiator" required>
              <el-input v-model="dialogForm.initiator" placeholder="请输入发起方" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抄送方" prop="sender">
              <el-input v-model="dialogForm.sender" placeholder="请输入抄送方" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告时间" prop="noticeDate" required>
              <el-date-picker 
                v-model="dialogForm.noticeDate" 
                type="datetime" 
                placeholder="选择日期时间" 
                style="width: 100%"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="模版ID" prop="templateId">
              <el-input v-model="dialogForm.templateId" placeholder="请输入模版ID" />
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="缩略图" prop="picUrl">
              <ImageUpload v-model="dialogForm.picUrl" :limit="1" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="公告内容" prop="content" required>
              <el-input 
                v-model="dialogForm.content" 
                type="textarea" 
                :rows="6"
                placeholder="请输入公告内容" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文件上传" prop="fileUrl">
              <FileUpload 
                v-model="dialogForm.fileUrl"
                :file-type="['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf', 'jpg', 'jpeg', 'png']"
                :file-size="10"
                :limit="5"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDialogSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { getNoticeList, addNotice, editNotice, removeNotice } from '@/api/house/notice'
import Pagination from '@/components/Pagination/index.vue'
import FileUpload from '@/components/FileUpload/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import useUserStore from '@/store/modules/user'
import dayjs from 'dayjs'
import { ArrowDown } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const noticeList = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogFormRef = ref()
const ids = ref([])
const single = ref(true)
const multiple = ref(true)

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  noticeTitle: '',
  noticeType: '',
  initiator: '',
  createDate: [], // 初始化为空数组
})

// 弹窗表单
const dialogForm = reactive({
  id: undefined,
  noticeTitle: '',
  noticeType: '',
  noticeNo: '',
  initiator: '',
  content: '',
  fileUrl: '',
  sender: '',
  noticeDate: '',
  createDate: '',
  lastModifyDate: '',
  templateId: '',
  templateName: '',
  communityId: '',
  communityName: '',
  picUrl:''
})

// 表单验证规则
const dialogRules = {
  noticeTitle: [
    { required: true, message: '请输入公告标题', trigger: 'blur' }
  ],
  noticeType: [
    { required: true, message: '请选择公告类型', trigger: 'change' }
  ],
  noticeNo: [
    { required: true, message: '请输入公告编号', trigger: 'blur' }
  ],
  initiator: [
    { required: true, message: '请输入发起方', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ],
  noticeDate: [
    { required: true, message: '请选择公告时间', trigger: 'change' }
  ],
  picUrl: [
    { required: true, message: '请上传缩略图', trigger: 'change' }
  ]
}



// 公告类型选项
const noticeTypeOptions = [
  { label: '业主大会公告', value: '业主大会公告' },
  { label: '日常管理公告', value: '日常管理公告' },
  { label: '违规行为公告', value: '违规行为公告' },
  { label: '治理进展公告', value: '治理进展公告' }
]

// 获取公告类型标签类型
const getNoticeTypeTagType = (type) => {
  const typeMap = {
    '业主大会公告': 'danger',
    '日常管理公告': 'primary',
    '违规行为公告': 'warning',
    '治理进展公告': 'success'
  }
  return typeMap[type] || 'info'
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 获取文件名
const getFileName = (url) => {
  if (!url) return ''
  // 从URL中提取文件名
  const fileName = url.split('/').pop()
  if (!fileName) return url
  
  // 去掉时间戳部分（假设时间戳是数字格式）
  // 匹配文件名中的时间戳模式，如 -1214896591864852481
  const nameWithoutTimestamp = fileName.replace(/-\d+\.(png|jpg|jpeg|gif|pdf|doc|docx|xls|xlsx|ppt|pptx|txt)$/i, '.$1')
  
  return nameWithoutTimestamp || fileName
}

// 获取列表
const getList = () => {
  loading.value = true
  // 构建查询参数，处理创建时间格式
  const params = {
    ...queryParams.value
  }
  // 调试日志
  console.log('原始查询参数:', queryParams.value)
  if (Array.isArray(params.createDate) && params.createDate.length === 2) {
    // 确保日期格式正确
    params.startCreateDate = dayjs(params.createDate[0]).format('YYYY-MM-DD HH:mm:ss')
    params.endCreateDate = dayjs(params.createDate[1]).format('YYYY-MM-DD HH:mm:ss')
    delete params.createDate
    console.log('转换后的参数:', params)
  } else {
    console.log('createDate不是有效的数组或长度不足2:', params.createDate)
  }
  getNoticeList(params).then(res => {
    noticeList.value = res?.rows || []
    total.value = res?.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  Object.keys(queryParams.value).forEach(key => {
    if (Array.isArray(queryParams.value[key])) {
      queryParams.value[key] = []
    } else if (key === 'startDate') {
      queryParams.value[key] = dayjs().format('YYYY-MM-DD') // 重置为今天
    } else {
      queryParams.value[key] = ''
    }
  })
  handleQuery()
}

// 选择变更
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  Object.assign(dialogForm, {
    id: undefined,
    noticeTitle: '',
    noticeType: '',
    noticeNo: '',
    initiator: '',
    content: '',
    fileUrl: '',
    sender: '',
    noticeDate: '',
    createDate: '',
    lastModifyDate: '',
    templateId: '',
    templateName: '',
    picUrl:'',
    communityId: userStore.communityId,
    communityName: userStore.communityName
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  if (!row) {
    const id = ids.value[0]
    row = noticeList.value.find(item => item.id === id)
  }
  isEdit.value = true
  Object.assign(dialogForm, row)
  
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  const delIds = row ? [row.id] : ids.value
  if (!delIds.length) return
  
  ElMessageBox.confirm('是否确认删除公告编号为"' + delIds + '"的数据项?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return Promise.all(delIds.map(id => removeNotice(id)))
  }).then(() => {
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 导入
const handleImport = () => {
  // 预留导入逻辑
  ElMessage.info('导入功能待实现')
}

// 导出
const handleExport = () => {
  proxy.download(
    'pms/notice/export',
    { ...queryParams.value },
    `notice_${new Date().getTime()}.xlsx`
  )
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  dialogFormRef.value?.resetFields()
}

// 保存弹窗
const handleDialogSave = () => {
  dialogFormRef.value.validate(valid => {
    if (valid) {
      const payload = { ...dialogForm }
      
      // 格式化日期字段
      if (payload.noticeDate) {
        payload.noticeDate = dayjs(payload.noticeDate).format('YYYY-MM-DD HH:mm:ss')
      }
      console.log(payload.fileUrl)
      const req = isEdit.value ? editNotice(payload) : addNotice(payload)
      req.then(() => {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        getList()
      }).catch(() => {
        ElMessage.error('保存失败')
      })
    }
  })
}



// 初始化
onMounted(() => {
  getList()
})
</script>

